/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import fs from 'fs';
import path from 'path';
import process from 'process';

import { isWindows } from '@ohos/hvigor-common';
import { gte } from 'semver';

import { executeBuild } from './execute.js';
import {GlobalExecute,globalVersionCommands,globalHelpCommands} from './global-execute.js';
import { initProjectWorkSpace } from './hvigor-installer.js';
import { checkNpmConifg, environmentHandler, executeInstallPnpm, isPnpmInstalled } from './pnpm.js';
import { BASE_NODE_VERSION, isHvigorDependencyUseNpm } from './util.js';
/**
 * 判断是否hvigorw参数是否为全局通用命令参数
 */
function executeGlobalCommand() {
  const args = process.argv.slice(2);
  const versionCommand = args.filter((arg) => globalVersionCommands.includes(arg));
  if(versionCommand.length > 0){
    GlobalExecute.version(args.toString());
  }
  const helpCommand = args.filter((arg) => globalHelpCommands.includes(arg));
  if(helpCommand.length > 0){
    GlobalExecute.help();
  }
}

/**
 * Hvigor通过命令行方式执行环境准备的入口
 */
function wrapper() {
  // 处理环境变量
  environmentHandler();

  // 执行全局命令
  executeGlobalCommand();

  // pnpm
  if (gte(process.version.slice(1), BASE_NODE_VERSION) && !isHvigorDependencyUseNpm()) {
    if (!isPnpmInstalled()) {
      checkNpmConifg();
      executeInstallPnpm();
    }
  }
  const ohpmBinPath = path.resolve(__dirname, '../../ohpm/bin/', isWindows() ? 'ohpm.bat' : 'ohpm');
  if (fs.existsSync(ohpmBinPath)) {
    process.env['ohpmBin'] = ohpmBinPath;
  }

  const hvigorProjectHome = initProjectWorkSpace();

  executeBuild(hvigorProjectHome);
}

wrapper();
